package com.leyou.user.service;

import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.utils.CodecUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * *
 * Created by IntelliJ IDEA.
 * Author: caoLei
 * Date: 2018/11/2
 * Time: 18:18
 * *
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    //可以让用户更好的找到
    private static final String KEY_PREFIX = "user:code:phone:";

    //设置有效时间
    private static final Long TIMEOUT = 5L;

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    /**
     * 校验手机和用户名
     * @param data
     * @param type
     * @return
     */
    public Boolean checkUser(String data, Integer type) {
        User record = new User();
        if (type == 1) {
            //用户名
            record.setUsername(data);

        } else if (type == 2) {
            //手机
            record.setPhone(data);
        } else {
            return null;
        }
        //true可用，
       return this.userMapper.selectCount(record)==0;
    }

    /**
     * 发送短信
     * @param phone
     * @return
     */
    public Boolean sendVerifyCode(String phone) {

        //判断手机号是否为空
        if (StringUtils.isBlank(phone)) {
            return null;
        }
        //生成验证码
        String code = NumberUtils.generateCode(6);

        try {
            //发送短信给sms
            //创建map集合 要与leyou-sms中的SmsListener中的封装的方法一致
            Map<String, String> msg = new HashMap<>();
            msg.put("phone", phone);
            msg.put("code", code);
            this.amqpTemplate.convertAndSend("leyou.sms.exchange", "sms.verify.code", msg);

            //将code存入redis
            this.redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, TIMEOUT, TimeUnit.MINUTES);
            return true;
        } catch (AmqpException e) {
            logger.error("发送短信失败。phone：{}， code：{}", phone, code);
            return false;
        }
    }

    /**
     * 注册
     * @param user
     * @param code
     * @return
     */
    public Boolean register(User user, String code) {
        //校验短信验证码，不符合直接返回false
        String cacheCode = this.redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if (!StringUtils.equals(cacheCode, code)) {
            return false;
        }

        //生成salt
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);

        //对密码加密
        user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));

        //强制设置不能指定的参数为null
        user.setId(null);
        user.setCreated(new Date());

        //添加到数据库
        boolean boo = this.userMapper.insertSelective(user) == 1;

        if (boo) {
            //删除redis中的记录
            this.redisTemplate.delete(KEY_PREFIX + user.getPhone());

        }
        return boo;
    }

    /**
     * 根据用户名和密码查询用户(登录)
     * @param username
     * @param password
     * @return
     */
    public User queryUser(String username, String password) {
        User record = new User();
        record.setUsername(username);
        //根据用户名查询用户
        User user = this.userMapper.selectOne(record);
        if (user == null) {
            return null;
        }
        //校验密码

        String password2 = CodecUtils.md5Hex(password, user.getSalt());
        if (!StringUtils.equals(user.getPassword(), password2)) {
            return null;
        }
        //用户名和密码都正确
        return user;
    }
}
